/*
 * Copyright (c) 2022. All rights reserved.
 * Please don't try to modify the code, because I don't know what the consequences will be.
 *
 *
 *
 *
 *
 *
 *
 */

package cc.zzone.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * Spring 获取 bean 工具类
 *
 * @author jinzhengze
 * @since 2022年4月24日
 */
@Component
public final class SpringUtil implements ApplicationContextAware {

    private static volatile ApplicationContext applicationContext = null;

    @Override
    @SuppressWarnings("NullableProblems")
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        // 双重检查 单例模式
        if (SpringUtil.applicationContext == null)
            synchronized (ApplicationContext.class) {
                if (SpringUtil.applicationContext == null)
                    SpringUtil.applicationContext = applicationContext;
            }
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }

    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }

    public static <T> T getBean(String name, Class<T> clazz) {
        return getApplicationContext().getBean(name, clazz);
    }
}
